package ni;

import java.io.*;
import java.net.*;

import main.ChatNI;
import cs.remoteapp.Hello;
import cs.remoteapp.Message;

/**
 * Executes receiving message on udp
 * Package  ni
 * Project ChatSystemG5 - INSA 4INFOA1 - 2013/2014
 * @author Thomas Vuillemin Martin Conant
 */
public class UdpReceiver extends Udp {
	
	private boolean running = true;
	
	/**
	 * Constructor which open a socket udp on the specified port
	 * @param port the port on which it is supposed to listen
	 * @param ni the object ChatNI
	 */
	public UdpReceiver(int port, ChatNI ni)
	{
		super(ni);
		this.port = port;
		openUdpSocket(this.port);
	}
	
	/**
	 * Constructor who use a previously open socket passed in parameter
	 * @param socket the previously open socket
	 * @param ni the object ChatNI
	 */
	public UdpReceiver(DatagramSocket socket, ChatNI ni)
	{	
		super(ni);
		this.socket = socket;
		this.port = socket.getLocalPort();
	}

	/**
	 * Listen for new message on the socket.
	 * When a message arrive, it deserialize it and send it to the ChatNI
	 */
	@Override
	public void run()
	{
		System.out.println("udpReceiver started");
		System.out.println("udpReceiver is now listening to port : " + this.port);
		while(running){
			byte[] buf = new byte[1024]; //256 first
			DatagramPacket packet = new DatagramPacket(buf, buf.length);
			
			try {
				this.socket.receive(packet);
				InetAddress senderAddress = packet.getAddress();
				//Deserialization
				ByteArrayInputStream fichier = new ByteArrayInputStream(packet.getData());			 
				ObjectInputStream ois = new ObjectInputStream(fichier);
				Message receivedMessage = (Message) ois.readObject();
				//sending the message to ChatNI
				ni.setMessageToProcess(receivedMessage);
				ni.setAdressOfSender(senderAddress);
				//starting the Chat NI
				System.out.println("I'm gonna interrupt ChatNI");
				ni.interrupt();
				//Tests
				/*closeSocket();
				System.out.println("close socket \n");
				System.exit(0);*/
			} catch (IOException | ClassNotFoundException e) {
				System.out.println("udpReceiver is no longer listening to port : " + this.port);
			}		
		}
	}

	/**
	 * Stop the thread of the udpReceiver
	 */
	public void stopReceiver() {
		this.running=false;
	}

}